<template>
    <!-- 每天最多发布3条 每条无线字数 -->
    <div class="wraps">
        <div :class="['homewarp', isEditing ? 'ishide' : '']">
            <div class="homewarp_calendar">
                <div class="calendartitle">
                    <div class="ctime">
                        <span @click="preMouth">
                            <v-icon name="icon_pre" :size="16"></v-icon>
                        </span>
                        <span>{{ `${years}/${mouths < 10 ? ('0' + mouths) : mouths}` }}</span>
                        <span @click="nextMouth">
                            <v-icon name="icon_next" :size="16"></v-icon>
                        </span>
                    </div>
                    <div class="addbtns" v-if="currentNote.length" @click="deleteNotes">
                        <v-icon style="color:#fff" name="icon_delete" :size="30"></v-icon>
                    </div>
                    <div class="addbtns" v-else @click="onClickEditor">
                        <v-icon style="color:#fff" name="icon_add" :size="30"></v-icon>
                    </div>
                </div>
                <div class="calendars" v-if="!loading">
                    <div class="weekitem" v-for="(item, index) in weeks" :key="item">{{ item }}</div>
                    <div :class="['calendars_item', item.ismouth ? 'ismouth' : '']"
                        v-for="(item, index) in [...Object.values(calendarList)]" :key="item.key">
                        <div :class="['day', item.istoday ? 'istoday' : '', item.key == currentIndex ? 'isSelect' : '']" @click="onSelectitem(item)">{{ item.day }}</div>
                        <div :class="['dot', item.note.length ? 'dotactive' : '']"></div>
                    </div>
                </div>
            </div>
            <div class="homewarp_lists">
                <div class="finshlists">
                    <div v-if="!currentNote.length" class="empty">{{ $t("common.btn.nodata") }}📂</div>
                    <div v-if="currentNote.length" class="finshlists_item" @click="onClickEditor">
                        <div class="showlists" v-html="currentNote"></div>
                    </div>
                </div>
            </div>
        </div>
        <div :class="['editors', isEditing ? 'isshow' : '']">
            <div class="editors_top">
                <div class="back" @click="onClickEditor">
                    <v-icon name="icon_back" :size="20"></v-icon>
                </div>
                <div class="title">{{ currentIndex }}</div>
                <div @click="onSavefn" class="saves">{{ $t("common.btn.save") }}</div>
            </div>
            <div class="toolbars">
                <toolbar></toolbar>
            </div>
            <div class="editors_warp">
                <div class="editwarp" @input="onchangetext" ref="noteHtmlRef" contenteditable="true" v-html="currentNote"
                    :data-hodle="$t('workTodos.limit', [maxlen])">
                </div>
            </div>
            <div :class="[iserror ? 'errors' : 'default']">
                {{ iserror ? $t('workTodos.limit.tip') : `${strlen}/${maxlen}`}}
            </div>
        </div>
    </div>
</template>
<script setup lang="ts">
import toolbar from '@/views/components/toolbar.vue';
import { message } from 'ant-design-vue';
const { t } = useI18n();
// 日程最大字数
const maxlen = 100;
// 输入的长度
const strlen = ref<any>(0)
const date = new Date();
const y = date.getFullYear();
const m = date.getMonth() + 1;
const d = date.getDate();
// 正在加载日历
const loading = ref<any>(true)
const iserror = ref<any>(false)
const calendarList = ref<any>({})
// 当前选择日期
const currentIndex = ref<any>(`${y}-${m}-${d}`)
const currentNote = ref<any>('')
// 日期
const years = ref<any>(y)
const mouths = ref<any>(m)
const weeks = ref<any>([t('workTodos.schedule.monday'), t('workTodos.schedule.tuesday'), t('workTodos.schedule.wednesday'), t('workTodos.schedule.thursday'), t('workTodos.schedule.friday'), t('workTodos.schedule.saturday'), t('workTodos.schedule.sunday')])
// 是否是编辑状态
const isEditing = ref<boolean>(false)
// 日程数据
const dataSource = ref<any>(null)
const noteHtmlRef = ref<any>(null)

// 初始化日历数据 
const initCalendar = (year: any, mouth: any) => {
    let times = new Date(year, mouth, 0);
    let tf_day = times.getDate();
    let pf_day = new Date(mouth - 1 == 0 ? year - 1 : year, mouth - 1 == 0 ? 12 : mouth - 1, 0).getDay();
    let pre_day = new Date(mouth - 1 == 0 ? year - 1 : year, mouth - 1 == 0 ? 12 : mouth - 1, 0).getDate();
    pf_day = pf_day == 0 ? 7 : pf_day;
    pre_day = pre_day - pf_day;
    // 前几位永远是最大的
    for (let pre = 0; pre < (7 - (7 - pf_day)); pre++) {
        let dateTime = `${year - 1}-${mouth - 1}-${pre_day++}`;
        calendarList.value[dateTime] = {
            day: pre_day,
            ismouth: false,
            note: [],
            key: dateTime
        };
    }
    for (let tod = 0; tod < tf_day; tod++) {
        let today = tod + 1;
        let dateTime = `${year}-${mouth}-${today}`;
        calendarList.value[dateTime] = {
            day: today,
            istoday: (today == d && year == y && mouth == m),
            ismouth: true,
            note: [],
            key: dateTime
        };
    }
    // 日历为42位制；, 后几位永远是最小的
    let len = 42 - Object.keys(calendarList.value).length;
    for (let tod = 0; tod < len; tod++) {
        let dateTime = `${year + 1}-${mouth + 1}-${tod + 1}`;
        calendarList.value[dateTime] = {
            day: tod + 1,
            ismouth: false,
            note: [],
            key: dateTime
        };
    }
    loading.value = false;
}
// 获取日程
const getNotes = async () => {
    try{
        const res = await window.electron.onGetDatas(1);
        dataSource.value = JSON.parse(res);
        Object.keys(calendarList.value).map((item: any) => {
            calendarList.value[item].note = dataSource.value[item] || [];
        })
    }catch(err){
        message.error(err.toString())
    }
}
// 删除日程
const deleteNotes = async () => {
    try{
        delete dataSource.value[currentIndex.value];
        await window.electron.onSetDatas(JSON.stringify(dataSource.value), 1);
        const currentData = calendarList.value[currentIndex.value];
        currentData.note = "";
        onSelectitem(currentData);
    }catch(err){
        message.error(err.toString())
    }
}
// 增加日程
const addNotes = async (note: any) => {
    try{
        dataSource.value[currentIndex.value] = note;
        await window.electron.onSetDatas(JSON.stringify(dataSource.value), 1);
        const currentData = calendarList.value[currentIndex.value];
        currentData.note = note;
        onSelectitem(currentData);
    }catch(err){
        message.error(err.toString())
    }
}
// 前一月
const preMouth = () => {
    mouths.value--;
    if (mouths.value <= 0) {
        mouths.value = 12;
        years.value--;
    }
    calendarList.value = {};
    initCalendar(years.value, mouths.value);
    getNotes();
    onSelectitem();
}
// 下一月
const nextMouth = () => {
    mouths.value++;
    if (mouths.value > 12) {
        mouths.value = 1;
        years.value++;
    }
    calendarList.value = {};
    initCalendar(years.value, mouths.value);
    getNotes();
    onSelectitem();
}
const onchangetext = (e: any) => {
    let str = e.target.innerText.replace(/\n/g, '').replace(/\s/g, '');
    iserror.value = str.length > maxlen;
    strlen.value = str.length;
}
// 保存
const onSavefn = async () => {
    const html = noteHtmlRef.value.innerHTML;
    let str = html.replace(/\<(\/)?.\>/g, '').replace(/\n/g, '').replace(/\s/g, '');
    //需要储存的数据  
    if(str.length > maxlen) {
        message.error(t("workTodos.limit.tip"));
    }
    else if(str.length === 0){
        message.error(t("workTodos.limit.empty"));
    }
    else {
        await addNotes(html);
        isEditing.value = false;
    }
}
// 选择日期
const onSelectitem = (item?: any) => {
    if (item && item.ismouth) {
        currentIndex.value = item.key;
        currentNote.value = item.note;
    }
    else{
        currentIndex.value = '';
        currentNote.value = '';
    }
}
// 新增/编辑/取消
const onClickEditor = async() => {
    isEditing.value = !isEditing.value;
    if(!isEditing.value){
        currentNote.value = '';
        noteHtmlRef.value.innerHTML = '';
    }
}
onMounted(async() => {
    // 1. 初始化日历
    initCalendar(years.value, mouths.value);
    // 2. 获取日程数据
    await getNotes();
    // 3. 定位到今日
    const currentData = calendarList.value[currentIndex.value];
    onSelectitem(currentData);
})
</script>
<style lang="less" scoped>
.wraps {
    height: 100%;
    width: 100%;
    padding: 8px;
    position: relative;
    .editors {
        display: flex;
        flex-direction: column;
        position: absolute;
        z-index: 99;
        left: 100%;
        top: 0;
        width: 100%;
        height: 100%;
        background-color: #fff;
        opacity: 0;
        transition: all .2s ease-in-out 0s;
        -webkit-app-region: no-drag;
        padding: 10px 20px;
        box-sizing: border-box;
        &_warp {
            -webkit-app-region: no-drag;
            font-size: 14px;
            width: 100%;
            margin-top: 10px;
            box-sizing: border-box;
            flex: 1;
            &>div {
                width: 100%;
                height: 100%;
                font-size: 16px;
                overflow: hidden;
                outline-style: none;
            }
        }
        .toolbars {
            display: flex;
        }
        &_top {
            margin-bottom: 16px;
            display: flex;
            align-items: center;
            .back{
                margin-right: 16px;
                -webkit-app-region: no-drag;
                cursor: pointer;
            }
            .title{
                font-size: 18px;
                font-weight: bold;
            }
            .saves {
                font-weight: bold;
                padding: 3px 6px;
                color: #475569;
                margin-left: auto;
                -webkit-app-region: no-drag;
                cursor: pointer;
                transition: all .1s ease-in 0s;
                &:hover {
                    color: #1C79F4;
                }
            }
        }
        
        &.isshow {
            opacity: 1;
            left: 0;
        }
        .errors {
            font-size: 12px;
            color: #f43f5e;
        }
        .default {
            font-size: 12px;
            color: var(--font-s);
            height: 60px;
        }
        .editwarp:empty::before{
            content: attr(data-hodle);
            font-size: .7rem;
            color: #64748B;
        }
    }
    .homewarp {
        display: flex;
        flex-direction: column;
        height: 100%;
        transition: all .3s ease-in 0s;
        &.ishide {
            transform: scale(.9) translateX(100px);
        }
        &_calendar {
            background-color: #fff;
            padding: 10px 10px;
            border-radius: 10px;
            .calendartitle {
                display: flex;
                align-items: center;
                justify-content: space-between;
                padding-bottom: 16px;
                .ctime {
                    display: flex;
                    align-items: center;
                    &>span:nth-of-type(1) {
                        display: flex;
                        align-items: center;
                        justify-content: center;
                        width: 20px;
                        height: 20px;
                        border-radius: 50%;
                        box-shadow: 0 2px 5px 0 rgba(0, 0, 0, 0.1);
                        cursor: pointer;
                        -webkit-app-region: no-drag;
                        transition: all .1s ease-in 0s;
                        &:active {
                            transform: scale(.8);
                        }
                        &:hover {
                            transform: scale(.9);
                        }
                    }
                    &>span:nth-of-type(2) {
                        margin: 0 16px;
                        font-weight: bold;
                        font-size: 18px;
                    }
                    &>span:nth-of-type(3) {
                        -webkit-app-region: no-drag;
                        display: flex;
                        align-items: center;
                        justify-content: center;
                        width: 20px;
                        height: 20px;
                        border-radius: 50%;
                        box-shadow: 0 2px 5px 0 rgba(0, 0, 0, 0.1);
                        cursor: pointer;
                        transition: all .1s ease-in 0s;
                        &:active {
                            transform: scale(.8);
                        }
                        &:hover {
                            transform: scale(.9);
                        }
                    }
                }
                .addbtns {
                    display: flex;
                    align-items: center;
                    justify-content: center;
                    width: 36px;
                    height: 36px;
                    border-radius: 50%;
                    background: #fcc000;
                    -webkit-app-region: no-drag;
                    cursor: pointer;
                    font-size: 22px;
                    &:hover{
                        background: #d4a827;
                    }
                }
            }
            .calendars {
                width: 100%;
                display: grid;
                grid-template-columns: repeat(7, 1fr);
                .ismouth {
                    color: var(--font-r);
                    opacity: 1;
                    .day {
                        width: 32px;
                        height: 32px;
                        display: flex;
                        justify-content: center;
                        align-items: center;
                        border-radius: 50%;
                        border: 1px solid transparent;
                        transition: all .1s;
                        cursor: pointer;
                        &:active {
                            border: 1px solid #ff3b2f;
                        }
                        &:hover {
                            border: 1px solid #ff3b2f;
                        }
                    }
                    .istoday {
                        color: #fff;
                        background: #ff3b2f;
                    }
                    .isSelect {
                        border: 1px solid #ff3b2f;
                    }
                }
                .dot {
                    width: 8px;
                    height: 8px;
                    border-radius: 50%;
                    margin-top: 3px;
                }
                .dotactive {
                    background-color: #ff3b2f;
                }
                &_item {
                    text-align: center;
                    color: var(--font-s);
                    font-size: 14px;
                    margin: 8px 0;
                    opacity: .3;
                    -webkit-app-region: no-drag;
                    display: flex;
                    flex-direction: column;
                    justify-content: center;
                    align-items: center;
                    transition: all .1s ease-in 0s;
                    .day {
                        width: 32px;
                        height: 32px;
                        display: flex;
                        justify-content: center;
                        align-items: center;
                        border-radius: 50%;
                        border: 1px solid transparent;
                        transition: all .2s ease 0s;
                        user-select: none;
                        cursor: pointer;
                    }
                }
                .weekitem {
                    color: #64748B;
                    font-weight: bold;
                    text-align: center;
                    font-size: 16px;
                    margin-bottom: 16px;
                    opacity: 1;
                }
            }
        }
        &_lists {
            flex: 1;
            height: 66px;
            margin-top: 8px;
            border-radius: 10px;
            background: #fff;
            transition: all 0.2s;
            &:hover{
                background: #FAEDC7;
            }
            .finshlists {
                display: flex;
                flex-direction: column;
                align-items: center;
                justify-content: center;
                padding: 10px;
                height: 100%;
                &:nth-of-type(2) {
                    margin-left: 8px;
                }
                &_item {
                    display: flex;
                    font-size: 14px;
                    height: 100%;
                    width: 100%;
                    overflow: hidden;
                    cursor: pointer;
                    -webkit-app-region: no-drag;
                    transition: all .1s ease-in 0s;
                    position: relative;
                    &>div {
                        margin-right: 8px;
                    }
                }
                .ltitle {
                    font-size: 11px;
                    font-weight: 100;
                }
                .empty {
                    text-align: center;
                    font-size: 14px;
                    color: #475569;
                }
            }
        }
    }
}
</style>
